import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { AuthService } from '../../shared/auth/auth.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Navigate } from '@ngxs/router-plugin';

@Component({
  selector: 'app-forget',
  templateUrl: './forget.component.html',
  styleUrls: ['./forget.component.scss'],
})
export class ForgetComponent implements OnInit {
  validateForm: FormGroup;

  constructor(
      private fb: FormBuilder,
      private store: Store,
      private auth: AuthService,
      private message: NzMessageService,
  ) {
    this.validateForm = this.fb.group({
      username: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required],
      confirm: ['', [Validators.required, this.checkConfirm()]],
    });
  }

  ngOnInit(): void {
  }

  submitForm() {
    if (this.validateForm.valid) {
      this.auth.forget(this.validateForm.getRawValue()).subscribe({
        next: () => {
          this.message.success(`密码重置成功，请重新登录`);
          this.store.dispatch(new Navigate(['/login']));
        },
        error: e => {
          if (e.status === 500 && !!e.error.message) {
            this.message.error(`${e.error.message}`);
          } else {
            this.message.error(`密码重置失败`);
          }
        },
      });
    }
  }

  checkConfirm() {
    return (control: AbstractControl) => {
      return !!control.value && control.value === this.validateForm.get('password')?.getRawValue()
          ? null : {confirmError: true};
    };
  }
}
